package com.loe.ktui.ui

import android.content.Context
import android.util.AttributeSet
import android.view.ViewGroup
import android.widget.FrameLayout

open class UiFrameLayout(id: String? = null) : UiGroup(id)
{
    open fun initUI(context: Context, view: KtFrameLayout)
    {
        super.initUI(context, view)

        isClick?.let { view.setClick(it) }

        // 递归子元素
        childs.forEach()
        {
            it.createView(context, view)
        }
    }

    /** 创建view */
    override fun createView(context: Context, parent: ViewGroup?): KtFrameLayout
    {
        return KtFrameLayout(context).also()
        {
            initUI(context, it)
            addToParent(parent, it)
        }
    }
}

fun Any.ui_FrameLayout(id: String? = null, block: (UiFrameLayout.() -> Unit)? = null): UiFrameLayout
{
    val ui = UiFrameLayout(id)
    block?.let { ui.it() }
    if (this is UiGroup) addChild(ui)
    return ui
}

open class KtFrameLayout : FrameLayout
{
    constructor(context: Context) : super(context)

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    {
        initXML(attrs)
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
    {
        initXML(attrs)
    }

    private fun initXML(attrs: AttributeSet)
    {
    }

    /********************************************** 点击 ****************************************/

    fun setClick(isClick: Boolean)
    {
        isAlpha = isClick
        isClickable = isClick
    }

    private var isAlpha = false

    override fun dispatchSetPressed(pressed: Boolean)
    {
        if (isAlpha) alpha = if (pressed || !isEnabled) 0.75f else 1f
        super.dispatchSetPressed(pressed)
    }

    override fun setEnabled(enabled: Boolean)
    {
        if (isAlpha) alpha = if (enabled) 1f else 0.75f
        super.setEnabled(enabled)
    }
}